package com.ruoyi.web.controller.repair;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.repair.domain.TWorkOrder;
import com.ruoyi.repair.domain.dto.WorkOrderQueryDTO;
import com.ruoyi.repair.service.ITWorkOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.repair.service.ITRepairRecordService;
import com.ruoyi.repair.service.ITFaultReportService;
import com.ruoyi.repair.domain.TRepairRecord;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 维修单Controller
 * 
 * @author ruoyi
 * @date 2025-09-24
 */
@RestController
@RequestMapping("/system/order")
public class TWorkOrderController extends BaseController
{
    @Autowired
    private ITWorkOrderService tWorkOrderService;

    @Autowired
    private ITRepairRecordService repairRecordService;

    @Autowired
    private ITFaultReportService tFaultReportService;

    /**
     * 查询维修单列表
     */
    @PreAuthorize("@ss.hasPermi('system:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(WorkOrderQueryDTO queryDTO)
    {
        startPage();
        // 如果是"我的维修"查询，设置当前用户ID作为assigneeId
        if (queryDTO.getMine() != null && queryDTO.getMine()) {
            Long currentUserId = getUserId();
            queryDTO.setAssigneeId(currentUserId);
        }
        List<TWorkOrder> list = tWorkOrderService.selectTWorkOrderListByDTO(queryDTO);
        return getDataTable(list);
    }

    /**
     * 导出维修单列表
     */
    @PreAuthorize("@ss.hasPermi('system:order:export')")
    @Log(title = "维修单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TWorkOrder tWorkOrder)
    {
        List<TWorkOrder> list = tWorkOrderService.selectTWorkOrderList(tWorkOrder);
        ExcelUtil<TWorkOrder> util = new ExcelUtil<TWorkOrder>(TWorkOrder.class);
        util.exportExcel(response, list, "维修单数据");
    }

    /**
     * 获取维修单详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:order:query')")
    @GetMapping(value = "/{workNo}")
    public AjaxResult getInfo(@PathVariable("workNo") String workNo)
    {
        return success(tWorkOrderService.selectTWorkOrderByWorkNo(workNo));
    }

    /**
     * 获取维修单状态履历（按工单号）
     */
    @PreAuthorize("@ss.hasPermi('system:order:query')")
    @GetMapping(value = "/{workNo}/history")
    public AjaxResult getHistory(@PathVariable("workNo") String workNo)
    {
        TRepairRecord query = new TRepairRecord();
        query.setWorkNo(workNo);
        List<TRepairRecord> list = repairRecordService.selectTRepairRecordList(query);
        return success(list);
    }

    /**
     * 新增维修单
     */
    @PreAuthorize("@ss.hasPermi('system:order:add')")
    @Log(title = "维修单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TWorkOrder tWorkOrder)
    {
        return toAjax(tWorkOrderService.insertTWorkOrder(tWorkOrder));
    }

    /**
     * 修改维修单
     */
    @PreAuthorize("@ss.hasPermi('system:order:edit')")
    @Log(title = "维修单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TWorkOrder tWorkOrder)
    {
        return toAjax(tWorkOrderService.updateTWorkOrder(tWorkOrder));
    }

    /**
     * 删除维修单
     */
    @PreAuthorize("@ss.hasPermi('system:order:remove')")
    @Log(title = "维修单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{workNos}")
    public AjaxResult remove(@PathVariable String[] workNos)
    {
        return toAjax(tWorkOrderService.deleteTWorkOrderByWorkNos(workNos));
    }

    /**
     * 确认维修单
     */
    @PreAuthorize("@ss.hasPermi('system:order:edit')")
    @Log(title = "维修单", businessType = BusinessType.UPDATE)
    @PutMapping("/confirm/{workNo}")
    public AjaxResult confirmWorkOrder(@PathVariable("workNo") String workNo)
    {
        try {
            // 获取维修单信息
            TWorkOrder workOrder = tWorkOrderService.selectTWorkOrderByWorkNo(workNo);
            if (workOrder == null) {
                return error("维修单不存在");
            }
            
            // 检查状态是否为待确认
            if (!"PENDING_CONFIRM".equals(workOrder.getStatusCode())) {
                return error("只有待确认状态的维修单才能确认");
            }
            
            // 更新状态为已确认
            workOrder.setStatusCode("CONFIRMED");
            int result = tWorkOrderService.updateTWorkOrder(workOrder);
            
            if (result > 0) {
                return success("确认成功");
            } else {
                return error("确认失败");
            }
        } catch (Exception e) {
            return error("确认失败：" + e.getMessage());
        }
    }

    /**
     * 拒绝确认维修单
     */
    @PreAuthorize("@ss.hasPermi('system:order:edit')")
    @Log(title = "维修单", businessType = BusinessType.UPDATE)
    @PutMapping("/reject/{workNo}")
    public AjaxResult rejectWorkOrder(@PathVariable("workNo") String workNo)
    {
        try {
            // 获取维修单信息
            TWorkOrder workOrder = tWorkOrderService.selectTWorkOrderByWorkNo(workNo);
            if (workOrder == null) {
                return error("维修单不存在");
            }
            
            // 检查状态是否为待确认
            if (!"PENDING_CONFIRM".equals(workOrder.getStatusCode())) {
                return error("只有待确认状态的维修单才能拒绝确认");
            }
            
            // 调用故障报修服务的拒绝承认方法，逻辑与拒绝承认一致
            String reportNo = workOrder.getRptNo();
            if (reportNo != null) {
                int result = tFaultReportService.rejectFaultReport(reportNo);
                if (result > 0) {
                    return success("拒绝确认成功，已重新分配给维修人员");
                } else {
                    return error("拒绝确认失败");
                }
            } else {
                return error("无法获取关联的报修单号");
            }
        } catch (Exception e) {
            return error("拒绝确认失败：" + e.getMessage());
        }
    }
}